package com.huitongjy.common.generator;

import java.util.Arrays;
import java.util.Iterator;

/**
 * 批量Id
 */
public class BatchKey implements Iterator<Long> {
    private Item[] items;
    private int index;
    private long value;

    public void add(Item item) {
        if(items==null) {
            items = new Item[]{item};
            value=items[0].begin;
        } else {
            Item[] copy = new Item[items.length + 1];
            System.arraycopy(items, 0, copy, 0, items.length);
            copy[items.length] = item;
            items = copy;
        }
    }

    @Override
    public boolean hasNext() {
        return value <= items[index].end;
    }

    @Override
    public Long next() {
        Long result = value;
        if(++value > items[index].end && index +1<items.length) {
            index++;
            value = items[index].begin;
        }
        return result;
    }

    static class Item {
        final long begin;
        final long end;

        Item(long begin, int length) {
            this.begin = begin;
            this.end = this.begin + length -1;
        }

        @Override
        public String toString() {
            return "{" + "\"begin\":" + begin + ", \"end\":" + end + "}";
        }
    }

    @Override
    public String toString() {
        return Arrays.toString(items);
    }
}
